import { defineStore } from 'pinia'
import { ref } from 'vue'
import { useMapStore } from '@/store/map'
import { useCarGoStore } from './cargo'
export const usePlayerStore = defineStore('player', () => {
  const { isWall } = useMapStore()
  const player = ref({
    x: 0,
    y: 0,
  })
  // 设置人物位置
  function setupPlayer(playerData) {
    player.value = playerData
  }
  // 移动人物
  function move(x, y) {
    const nextPositions = {
      x: player.value.x + x,
      y: player.value.y + y,
    }

    // 如果下一个坐标是墙直接结束
    if (isWall(nextPositions)) return
    // 如果下一个位置是箱子
    const { findCargo, moveCargo } = useCarGoStore()
    const cargo = findCargo(nextPositions)
    //找到箱子进行移动，箱子移动会返回下一个状态，如何是墙或者后一个是箱子就return 不移动人物
    if (cargo) {
      const isFalg = moveCargo(cargo, x, y)
      if (!isFalg) return
    }
   

    
    setupPlayer(nextPositions)
  }

  // 向上
  function moveUp() {
    move(0, -1)
  }
  // 向下
  function moveDown() {
    move(0, 1)
  }
  // 向左
  function moveLeft() {
    move(-1, 0)
  }
  //向右
  function moveRight() {
    move(1, 0)
  }

  return { player, setupPlayer, moveUp, moveDown, moveLeft, moveRight }
})
